package org.boofcv.video.slice;

import boofcv.abst.fiducial.QrCodeDetector;
import boofcv.alg.fiducial.qrcode.QrCode;
import boofcv.factory.fiducial.FactoryFiducial;
import boofcv.ohos.ConvertBitmap;
import boofcv.struct.image.GrayU8;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;
import org.boofcv.video.ResourceTable;

import java.io.FileNotFoundException;
import java.io.InputStream;

import static ohos.media.image.common.PixelFormat.ARGB_8888;

public class BitmapSlice extends AbilitySlice {
    public static final int PICK_IMAGE = 1;

    private Image imageView;
    private Text textView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_bitmap);

        imageView = (Image) findComponentById(ResourceTable.Id_img_show);
        textView = (Text) findComponentById(ResourceTable.Id_text_bitmap_decoded);
        findComponentById(ResourceTable.Id_text_image).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                // Respond to the user clicking the select image button by opening up an image select
                Operation operation = new Intent.OperationBuilder()
                        .withAction(IntentConstants.ACTION_CHOOSE)
                        .build();
                Intent intente = new Intent();
                intente.setType("image/*");
                intente.setOperation(operation);
                startAbilityForResult(intente, PICK_IMAGE);
            }
        });
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);

        // Abort if anything goes wrong or the user canceled
        if (requestCode != PICK_IMAGE || resultCode != -1) {
            return;
        }
        if (resultData == null) {
            return;
        }
        String uriString = resultData.getUriString();
        if (uriString == null) {
            return;
        }
        uriString = uriString.replace("content://", "dataability:///");

        try {
            // Load the image
            InputStream inputStream = DataAbilityHelper.creator(getContext()).obtainInputStream(Uri.parse(uriString));
            PixelMap original = ImageSource.create(inputStream,
                    new ImageSource.SourceOptions()).createPixelmap(new ImageSource.DecodingOptions());
            // Display the image
            imageView.setPixelMap(original);

            // Scale the image. We are doing this to keep memory consumption down (could be an
            // old device) and for fast processing
            double factor = Math.max(original.getImageInfo().size.width / 1024.0, original.getImageInfo().size.height / 1024.0);
            int newWidth = (int) (original.getImageInfo().size.width / factor);
            int newHeight = (int) (original.getImageInfo().size.height / factor);
            PixelMap scaled = PixelMap.create(original, ConvertBitmap.createOpts(newWidth, newHeight, ARGB_8888));

            // Convert it into a BoofCV image that can be processed
            GrayU8 gray = new GrayU8(1, 1);
            ConvertBitmap.bitmapToBoof(scaled, gray, null);

            // Send it through the QR code detector
            QrCodeDetector<GrayU8> detector = FactoryFiducial.qrcode(null, GrayU8.class);
            detector.process(gray);

            StringBuilder text = new StringBuilder();
            text.append("Total Detected = ");
            text.append(detector.getDetections().size());
            text.append("\n");

            for (QrCode qr : detector.getDetections()) {
                text.append(qr.message);
                text.append("\n");
            }

            textView.setText(text.toString());
        } catch (FileNotFoundException | DataAbilityRemoteException e) {
            e.printStackTrace();
        }
    }
}
